package com.imti.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.imti.api.Constants;
import com.imti.bean.Account;
import com.imti.bean.dto.LoginDTO;
import com.imti.config.BusinessException;
import com.imti.mapper.AccountMapper;
import com.imti.service.AccountService;
import com.imti.utils.JwtUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author T470S
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {

    @Override
    public Map<String, Object> login(LoginDTO loginDTO) {

        Map<String, Object> resultMap = new HashMap<>(2);

        Account account = lambdaQuery().eq(Account::getPhone, loginDTO.getPhone()).one();
        // 用户手机号不存在
        if (ObjectUtil.isNull(account)){
            throw new BusinessException(Constants.ACCOUNT_PHONE_NOT_EXISTS_CODE, Constants.ACCOUNT_PHONE_NOT_EXISTS);
        }

        // 密码错误
        if(!account.getPswd().equals(DigestUtils.md5Hex(loginDTO.getPassword()))){
            throw new BusinessException(Constants.ACCOUNT_PASSWORD_ERROR_CODE, Constants.ACCOUNT_PASSWORD_ERROR);
        }

        // 获取登录token
        Map<String, String> tokenMap = new HashMap<>(3);
        tokenMap.put("userId", account.getAccId() + "");
        tokenMap.put("phone", account.getPhone());
        String token = JwtUtils.genereteToken(tokenMap);

        resultMap.put("token", token);
        resultMap.put("expire", Constants.PROJECT_TOKEN_EXPIRE_TIME);
        return resultMap;
    }
}
